﻿using System;
using System.Collections.Generic;
using Microsoft.SharePoint;
using WoltersKluwer.SPChainGang.Core.Data.Repository;
using WoltersKluwer.SPChainGang.Core.Util;
using WoltersKluwer.SPChainGang.Core.Data.Entity;

namespace WoltersKluwer.SPChainGang.Core.Data
{
    public static class RepositoryLocator
    {
        static readonly Dictionary<Type, Type> cachedInstances = new Dictionary<Type, Type>();

        static RepositoryLocator()
        {
            Register<IConfigurationRepository, ConfigurationRepository>();
            Register<IReportsRepository<string,ReportFileRecord>, CSVReportsRepository>();
        }

        static void Register<T, TKRepository>() where TKRepository : T
        {
            var type = typeof(T);
            if (!cachedInstances.ContainsKey(type))
                cachedInstances.Add(type, typeof(TKRepository));
        }

        public static T Get<T>(String siteUrl)
        {
            Type repositoryType;
            var repositoryInterfaceType = typeof(T);
            if (cachedInstances.TryGetValue(repositoryInterfaceType, out repositoryType))
                return (T)FastObjectFactory.CreateObject(repositoryType, siteUrl);
            
            throw new ArgumentOutOfRangeException(
                repositoryInterfaceType.Name,
                string.Format("Repository '{0}' not found", repositoryInterfaceType.Name));
        }

        public static T Get<T>(SPWeb web)
        {
            Type repositoryType;
            var repositoryInterfaceType = typeof(T);
            if (cachedInstances.TryGetValue(repositoryInterfaceType, out repositoryType))
                return (T)FastObjectFactory.CreateObject(repositoryType, web);

            throw new ArgumentOutOfRangeException(
                repositoryInterfaceType.Name,
                string.Format("Repository '{0}' not found", repositoryInterfaceType.Name));
        }
    }
}
